// 再写两个函数 1.判断token有无效，2.根据token获取用户数据
// https://www.bilibili.com/read/cv24700373/
const jwt = require('jsonwebtoken')
const omit = require('lodash/omit')
const { staff_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
exports.checkToken = (token) => {
    try {
        var decoded = jwt.verify(token, 'shhhhh')
        return decoded;
    } catch (e) {
        console.log(e)
        return {
            state: 'noPass',
            msg: '校验失败'
        }
    }

}
exports.main = async (event, context) => {
    const token = event.data;
    if (!token) {
        return { state: 'noPass', msg: '未登录' }
    }
    try {
        const decoded = jwt.verify(token, 'shhhhh');
        console.log('token解码', decoded)
        if (decoded && decoded.account) {
            const result = await db.collection(staff_collection)
                .where({ account: decoded.account })
                .get();

            if (!result.data.length) {
                return { state: 'noPass', msg: '用户不存在' }
            };

            const staff = result.data[0];
            const userInfo = omit(staff, ['_id', 'password'])
            return { state: 'pass', msg: '登录成功', data: userInfo, token }
        }
    } catch (err) {
        console.log(err)
        return { state: 'noPass', msg: '校验错误' }
    }
}